<template>
  <div class="modal">
    <!-- 遮罩层 -->
    <div class="mask" @click="changeIsShowLoginModal(false)"></div>
    <!-- 登录框 -->
    <div class="loginbox">
      <!-- 关闭按钮 -->
      <div class="close" @click="changeIsShowLoginModal(false)"></div>
      <!-- 切换登录导航 -->
      <section class="nav">
        <a
          href="#"
          :class="{ active: isShowContent }"
          @click="isShowContent = true"
          >手机号登录</a
        >|
        <a href="#" :class="{ active: !isShowContent }" @click="showQrCode"
          >微信扫码登录</a
        >
      </section>
      <div class="content">
        <div class="phoneLogin" v-show="isShowContent">
          <div class="row">
            <input
              type="text"
              class="ipt"
              v-model="phoneNumber"
              placeholder="请输入手机号"
            />
          </div>
          <div class="row">
            <slide-verify
              :l="42"
              :r="20"
              :w="362"
              :h="140"
              @success="onSuccess"
              @fail="onFail"
              @refresh="onRefresh"
              :style="{ width: '100%' }"
              class="slide-box"
              ref="slideBlock"
              :slider-text="msg"
            ></slide-verify>
          </div>
          <div class="row">
            <input
              type="text"
              class="ipt"
              placeholder="请输入短信验证码"
              v-model="code"
            />

            <button class="msg-btn" @click="getCode" v-show="!isShowCount">
              获取验证码
            </button>
            <button class="msg-btn" v-show="isShowCount">
              {{ `${count}s` }}
            </button>
          </div>

          <div class="row">
            <button class="login-btn" @click="submitFn">登录</button>
          </div>
        </div>
        <div id="weixin" class="codeLogin" v-show="!isShowContent">
          二维码登录
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapActions, mapMutations } from "vuex";

import { validatePhoneNumber } from "@/utils/index";

import { SendSMSAPI } from "@/request/api";
import { PhoneLoginAPI } from "@/request/api";
import { WXLoginAPI } from "@/request/api";
import { BindPhoneAPI } from "@/request/api";
import { userProfilesAPI } from "@/request/api";

export default {
  /* created() {
    // let mycode = 123;
    this.$nextTick(async () => {
      let mycode = this.$route.query.code;
      console.log("this,$route:", this.$route.query.code);
      if (!mycode) return;
      let res = await WXLoginAPI({
        code: mycode,
      });
      // console.log("WXLoginAPI:", res);
      // 0 400 407
      if (res.code == 0) {
        // 正常情况
      } else if (res.code == 400) {
        // 提醒用户重新扫码
      } else if (res.code == 407) {
        // 提醒用户通过手机号登录
        alert("请使用手机号重新登录 ");
        // 模态框重新显示
        this.changeIsShowLoginModal(true);
        // 存储uuid.(登录时候获取)
        localStorage.setItem("uuid", res.uuid);
      }
    });
  }, */
  data() {
    return {
      // 登录界面控制
      isShowContent: true,
      // 滑块提示信息
      msg: "向右滑动->",
      // 手机号
      phoneNumber: "",
      // 倒计时
      count: 59,
      // 按钮切换
      isShowCount: false,
      // 验证码
      code: "",
    };
  },
  methods: {
    ...mapMutations({
      changeIsShowLoginModal: "showModal/changeIsShowLoginModal",
      changeIsLogin: "isLogined/changeIsLogin",
      changeIsIsShowToast: "showToast/changeIsIsShowToast",
      // showToastFn() {
      //   this.changeIsIsShowToast(true);
      //   setTimeout(() => {
      //     this.changeIsIsShowToast(false);
      //   }, 1500);
      // },

      showQrCode() {
        this.isShowContent = false;
        //获取二维码 并展示
        // 申请微信登录二维码
        let _this = this;
        new WxLogin({
          id: "weixin",
          appid: "wx67cfaf9e3ad31a0d", // 这个appid要填死
          scope: "snsapi_login",
          // 扫码成功后重定向的接口
          redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
          // state填写编码后的url
          state: encodeURIComponent(
            window.btoa("http://127.0.0.1:8080" + _this.$route.path)
          ),
          // 调用样式文件
          href: "data:text/css;base64,LmltcG93ZXJCb3ggLnRpdGxlLA0KLmltcG93ZXJCb3ggLmluZm8gew0KICBkaXNwbGF5OiBub25lOw0KfQ0K",
        });
      },
    }),
    ...mapActions({
      asyncChangeIsShowToast: "showToast/asyncChangeIsShowToast",
      asyncChangeUserInfo: "userInfo/asyncChangeUserInfo",
    }),

    // 拼图成功
    onSuccess(times) {
      let ms = (times / 1000).toFixed(1);
      this.msg = "login success, 耗时 " + ms + "s";
    },
    // 拼图失败
    onFail() {
      this.onRefresh(); // 重新刷新拼图
    },
    // 拼图刷新
    onRefresh() {
      this.msg = "再试一次";
    },

    //倒计时方法
    countdown() {
      this.isShowCount = true; //显示倒计时
      let timer = setInterval(() => {
        this.count--; //递减
        if (this.count == 0) {
          //停止定时器
          clearInterval(timer);
          //显示回  获取验证码
          this.isShowCount = false;
          //初始化count
          this.count = 59;
        }
      }, 1000);
    },

    //1. 手机输入正确(不为空，格式正确）， 不正确 return
    //正则验证  reg.test(string)  成功 返回true 都不匹配返回false
    // 工具函数（传入手机号）返回 是成功true还是失败false
    toVerity() {
      if (!validatePhoneNumber(this.phoneNumber)) {
        // 01. 最初方式
        // alert("请输入正确的手机号码");

        // 02. 初步优化
        // this.changeIsIsShowToast({
        //   isShow: true,
        //   msg: "请输入正确的手机号码",
        //   type: "danger",
        // });
        // setTimeout(() => {
        //   this.changeIsIsShowToast({
        //     isShow: false,
        //   });
        // }, 2000);
        // 03. 最后最终优化---封装在异步方法
        this.asyncChangeIsShowToast({
          msg: "请输入正确的手机号码",
          type: "danger",
        });
        return false;
      }
      // 2. 滑块验证码 需要正确， 不正确return
      // 如果是向右滑动 或者是 再试一次 都是表示不成功
      if (this.msg == "向右滑动" || this.msg == "再试一次") {
        alert("请进行滑块验证");
        return false;
      }
      return true;
    },

    // 获取验证码
    async getCode() {
      if (!this.toVerity()) return;
      //3. 获取验证码功能（给后台发起一个请求），发送成功后还有一个倒计时的效果59s...
      //发请求
      let res = await SendSMSAPI({
        phone: this.phoneNumber.trim(),
      });
      // console.log("发请求结果：", res);

      if (!res) return;
      if (res.data.code == 0) {
        alert("短信验证码发送成功");
        //倒计时（ 循环interval递减数字count ）
        this.countdown();
      }
    },

    // 登录
    async submitFn() {
      // 1. 手机输入正确(不为空，格式正确）， 不正确 return
      // 2. 滑块验证码 需要正确， 不正确return
      if (!this.toVerity()) {
        // console.log("登录成功");
        return;
      }
      // 3. 输入短信验证码（前端没有手机验证码，只做手机验证码）
      if (this.code.trim() == "") {
        alert("请输入验证码");
        return;
      }
      let uuid = localStorage.getItem("uuid");
      let res = null;
      if (uuid) {
        res = await BindPhoneAPI({
          verifyCode: this.code.trim(),
          phone: this.phoneNumber.trim(),
          uuid,
        });
      } else {
        res = await PhoneLoginAPI({
          verifyCode: this.code,
          phone: this.phoneNumber,
        });
      }
      // 4. 发起登录请求
      // console.log("发起登录请求");
      // let res = await PhoneLoginAPI({
      //   verifyCode: this.code,
      //   phone: this.phoneNumber,
      // });
      if (!res) return;
      // 1. 提示登录成功
      // alert("登录成功");

      // console.log("成功请求");
      this.changeIsIsShowToast(true);
      // this.showToastFn(true);
      // 2. 保存token值
      localStorage.setItem("x-auth-token", res["x-auth-token"]);
      // 3. 登录模态窗隐藏
      this.changeIsShowLoginModal(false);
      // 4. 登录状态更新
      this.changeIsLogin(true);
      // 5. 删除uuid  
      // console.log("uuid");
      localStorage.removeItem("uuid");
      // 6. 清楚地址栏的code
      this.$router.push(this.$route.path);
      // 7. (发送请求)获取用户信息
      // let uRes = await userProfilesAPI();
      // console.log("获取用户信息:", uRes);
      this.asyncChangeUserInfo()
    },
  },
};
</script>

<style lang="less" scoped>
.modal {
  width: 100%;
  height: 100%;
  position: fixed;
  left: 0;
  top: 0;
  .mask {
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
  }
  .loginbox {
    width: 555px;
    height: 423px;
    background-color: pink;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
    background: url("../assets/img/login-box-bg.png");
    .close {
      position: absolute;
      right: 50px;
      top: 10px;
      width: 22px;
      height: 22px;
      background: url("../assets/img/close.png");
    }
    .nav {
      display: flex;
      justify-content: center;
      padding-top: 50px;
      font-size: 20px;
      a {
        text-decoration: none;
        color: #9b9ab3;
        padding: 0 15px;
        &.active {
          color: #030303;
        }
      }
    }
    .content {
      width: 355px;
      margin: 20px auto 0;
      height: 200px;
      .phoneLogin {
        .row {
          display: flex;
          margin-bottom: 20px;
        }
        .ipt {
          outline: none;
          flex: 1;
          height: 48px;
          padding-left: 10px;
        }
        button {
          border: none;
          cursor: pointer;
          line-height: 48px;
        }
        .msg-btn {
          padding: 0 10px;
          margin-left: 5px;
        }
        .login-btn {
          color: #fff;
          width: 100%;
          background-color: #0a328e;
        }
      }
      #weixin {
        /* background-color: #fcf; */
        display: flex;
        justify-content: center;
      }
    }
  }
}

/deep/.slide-box {
  width: 100%;
  position: relative;
  box-sizing: border-box;
  canvas {
    position: absolute;
    left: 0;
    top: -120px;
    display: none;
    width: 100%;
    box-sizing: border-box;
  }
  .slide-verify-block {
    width: 85px;
    height: 136px;
  }
  .slide-verify-refresh-icon {
    top: -120px;
    display: none;
  }
  &:hover {
    canvas {
      display: block;
    }
    .slide-verify-refresh-icon {
      display: block;
    }
  }
}
</style>
